const OSS = require('ali-oss')
const co = require('co')

const config = require('../config/')
const env = process.env.NODE_ENV
const ossConf = config[env].ossConf

const client = new OSS({
  region: ossConf.region,
  accessKeyId: ossConf.accessKeyId,
  accessKeySecret: ossConf.accessKeySecret,
  bucket: ossConf.bucket
})

exports.listInner = async (query) => {
  let result
  let defaultParas = {
    "max-keys": 1000
  }
  let q = Object.assign({}, query, defaultParas)
  await co(function* () {
    result = yield client.list(q)
  }).catch(err => {
    console.error(err)
  })
  return result
}

exports.list = async (ctx, next) => {
  let query = ctx.query
  await co(function* () {
    let result = yield client.list(query)
    ctx.body = result
  }).catch(err => {
    ctx.body = err
  })
}

exports.signatureUrlInner = async (objectKey) => {
  return client.signatureUrl(objectKey)
}

exports.signatureUrl = async (ctx, next) => {
  let query = ctx.query
  let url = client.signatureUrl(query.objectKey)
  ctx.body = { url }
}

exports.uploadInner = async (objectKey, filename) => {
  let result
  await co(function* () {
    result = yield client.put(objectKey, filename)
  }).catch(err => {
    result = err
  })
  return result
}

exports.upload = async (ctx, next) => {
  let body = ctx.request.body
  await co(function* () {
    let result = yield client.put(body.objectKey, body.filename)
    ctx.body = result
  }).catch(err => {
    ctx.body = err
  })
}